package com.xuliugen.security.web.controller.async;

import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

/**
 * 异步请求Controller
 * Created by xuliugen on 2017/11/5.
 */
@RestController
@RequestMapping(value = "/async")
public class AsyncController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private final MockQueue mockQueue;
    private final DeferredResultHolder deferredResultHolder;

    @Autowired
    public AsyncController(MockQueue mockQueue, DeferredResultHolder deferredResultHolder) {
        this.mockQueue = mockQueue;
        this.deferredResultHolder = deferredResultHolder;
    }

    /**
     * 使用DeferredResult实现异步请求
     * @return
     * @throws Exception
     */
    @RequestMapping("/order")
    public DeferredResult<String> order() throws Exception {
        logger.info("主线程开始");

        String orderNumber = RandomStringUtils.randomNumeric(8);
        mockQueue.setPlaceOrder(orderNumber);

        DeferredResult<String> result = new DeferredResult<>();
        deferredResultHolder.getMap().put(orderNumber, result);

        return result;
    }

}
